package cn.tedu._03vehicle.controller;

import cn.tedu._03vehicle.base.response.JsonResult;
import cn.tedu._03vehicle.mapper.NoticeMapper;
import cn.tedu._03vehicle.pojo.vo.NoticeListVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.Serializable;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Tag(name="01-资讯管理模块")
@Slf4j
@RestController
@RequestMapping("/v1/notice")
public class NoticeController {
    @Autowired
    private NoticeMapper noticeMapper;
    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;

    @GetMapping("list")
    @Operation(summary = "1.公告列表")
    @ApiOperationSupport(order = 10)
    public JsonResult list() {
        /*
            第1个：数据类型选择 - Redis中的字符串string类型
            第2个：key-value设计 - {"notice_index": "[{},{},{},...]"}

            1.到Redis中查询首页的数据
            2.如果Redis中有数据，直接返回结束
            3.如果Redis中没有数据，到MySQL中查询数据
            4.将查询到的数据缓存到Redis中，缓存时间为30秒
         */
        Serializable noticeIndex = redisTemplate.opsForValue().get("notice_index");
        if (noticeIndex != null) {//缓存中存在数据
            log.debug("从Redis中查询到首页数据：{}", noticeIndex);
            return JsonResult.ok(noticeIndex);
        }
        //缓存中不存在数据
        List<NoticeListVO> noticeListVO = noticeMapper.selectNoticeList();
        //缓存到Redis中30秒
        redisTemplate.opsForValue().set("notice_index", (Serializable) noticeListVO, 30,TimeUnit.SECONDS);
        log.debug("从MySQL中查询到首页数据：{}", noticeListVO);
        return JsonResult.ok(noticeListVO);
    }
}
